package util;

import java.net.InetSocketAddress;

public class Picture implements Comparable {
	private byte[] jpeg;
	private long time;
	private long lag;
	private boolean isSync;
	private InetSocketAddress addr;

	/**
	 * Constructs the class and creates a picture object
	 * 
	 * @param data
	 *            the picture data as a byte array
	 * @param addr 
	 * @param camera
	 *            camera number
	 */
	public Picture(byte[] data, InetSocketAddress addr) {
		time = 1000L
				* ((getUnsigned(data, 25) << 24)
						+ (getUnsigned(data, 26) << 16)
						+ (getUnsigned(data, 27) << 8) + (getUnsigned(data, 28)))
				+ 10L * getUnsigned(data, 29);

		jpeg = data;		
		this.addr = addr;
		// System.out.println(time);
	}

	private long getUnsigned(byte[] data, int pos) {
		return data[pos] < 0 ? 256 + data[pos] : data[pos];
	}
	
	/**
	 * @return hostName
	 */
	public String getHostName() {
		return addr.getHostName();
	}
	
	public InetSocketAddress getAddr(){
		return addr;
	}

	/**
	 * @return timestamp of this image
	 */
	public long getTime() {
		return time;
	}

	/**
	 * @return picture data as a byte array
	 */
	public byte[] getJpeg() {
		return jpeg;
	}

	/**
	 * Set difference between timestamp and current time in ms
	 */
	public void setLag() {
		lag = System.currentTimeMillis() - time;
	}

	/**
	 * @return time in ms defined by setLag()
	 */
	public long getLag() {
		return lag;
	}

	/**
	 * @return delay calculated by the difference between timestamp and current
	 *         time in ms
	 */
	public long getDelay() {
		return System.currentTimeMillis() - time;
	}

	/**
	 * @return timestamp of this image in the form of HHMMSS
	 */
	public String getHHMMSS() {
		long timeSek = time / 1000;
		long sek = timeSek % 60;
		long min = (timeSek / 60) % 60;
		long hour = (timeSek / 3600) % 24;
		return Long.toString(hour * 10000 + min * 100 + sek);
	}

	/**
	 * @param p
	 *            the reference object with which to compare. true if this
	 *            object is the same as the obj argument; false otherwise.
	 */
	@Override
	public boolean equals(Object p) {
		if (p instanceof Picture) {
			Picture ps = (Picture) p;
			return (this.compareTo(ps) == 0) && (addr.equals(ps.addr));
		} else {
			return false;
		}
	}

	/**
	 * Compares this object with the specified object for order.
	 * 
	 * @return A negative integer, zero, or a positive integer as this object is
	 *         less than, equal to, or greater than the specified object.
	 */
	public int compareTo(Object p) {
		if (p instanceof Picture) {
			return (int) (this.time - ((Picture) p).time);
		}
		return -1;

	}

	/**
	 * Set true if this picture was synchronized.
	 * 
	 * @param isSync
	 *            set true for synchronized mode.
	 */
	public void setSync(boolean isSync) {
		this.isSync = isSync;
	}

	/**
	 * @return true of this picture was synchronized else false
	 */
	public boolean getSync() {
		return isSync;
	}

}
